#include<iostream>
#include<vector>
#include<algorithm>
using std::max;
using std::vector;


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.size() < 2) return 0;
        int buy1 = -prices[0], buy2 = -prices[0], sell1 = 0, sell2 = 0;
        int n = prices.size();
        int oldBuy1, oldSell1, oldBuy2;
        for (int i = 1; i < n; i++) {
            oldBuy1 = buy1;
            buy1 = max(buy1, -prices[i]);
            oldSell1 = sell1;
            sell1 = max(buy1 + prices[i], sell1);
            oldBuy2 = buy2;
            buy2 = max(oldSell1 - prices[i], buy2);
            sell2 = max(sell2, oldBuy2 + prices[i]);

        }
        return max(sell1, sell2);
    }
};